package tools.action.view {
	import tools.event.ActionEditorEvent;
	import tools.model.ActionInfo;
	import tools.model.EditorConfig;
	import tools.utils.bindSetter;

	import org.aswing.ListModel;
	import org.aswing.event.TableCellEditEvent;
	import org.aswing.table.PropertyTableModel;
	import org.aswing.table.sorter.TableSorter;
	import org.robotlegs.mvcs.Mediator;

	/**
	 * @author zhangming.luo
	 */
	public class ActionEditorMediator extends Mediator {
		[Inject]
		public var view : ActionEditorPanel;
		[Inject]
		public var config : EditorConfig;

		override public function onRegister() : void {
			super.onRegister();
			addViewListener(ActionEditorEvent.ADD_ACTION, dispatch);
			addViewListener(ActionEditorEvent.REMOVE_ACTION, dispatch);
			addViewListener(ActionEditorEvent.ADD_FRAME_TO_ACTION, dispatch);
			addViewListener(ActionEditorEvent.REMOVE_FRAME_FROM_ACTION, dispatch);
			addViewListener(ActionEditorEvent.CHANGE_FRAME_POSITION, dispatch);
			addViewListener(ActionEditorEvent.SELECTED_ACTION_CHANGED, onActionSelected);
			addViewListener(ActionEditorEvent.SELECTED_ACTIONFRAME_CHANGED, onActionFrameSelected);
			view.actionTable.addEventListener(TableCellEditEvent.EDITING_STOPPED, handleEdited);
			bindSetter(handleActionChange, config, "actionList").watch();
			bindSetter(handleFrameChange, config, "allFrameList").watch();
			bindSetter(handleSelectdAction, config, "curAction").watch();
		}

		private function handleEdited(event : TableCellEditEvent) : void {
			var list : ListModel = PropertyTableModel(TableSorter(view.actionTable.getModel()).getTableModel()).getList();
			var item : ActionInfo = list.getElementAt(event.getRow());
			// 分发一下事件
		}

		private function onActionFrameSelected(e : ActionEditorEvent) : void {
		}

		private function onActionSelected(e : ActionEditorEvent) : void {
			config.curAction = e.action;
		}

		private function handleSelectdAction() : void {
			view.actionFrameList.setListData(config.curAction.frameList);
		}

		private function handleFrameChange() : void {
			view.allFrameList.setListData(config.allFrameList);
		}

		private function handleActionChange() : void {
			view.actionListModel.clear();
			view.actionListModel.appendAll(config.actionList);
		}
	}
}
